package com.game.api.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.game.common.utils.MyUtils;
import com.game.core.resp.ResponeData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler,
                                            Exception ex) {
        System.err.println("=====================全局异常信息捕获=======================");
        String msg = "";
        if (ex instanceof HttpRequestMethodNotSupportedException) {
            msg = ex.getMessage();
        } else {
            msg = "获取接口失败!";
            ex.printStackTrace();
        }
        log.info("调用接口: " + ex.getMessage() + "\n" + MyUtils.getExceptionAllinformation(ex));
        try {
            ResponeData responeData = ResponeData.builder().build().fail(msg);
            String jsonString = JSON.toJSONString(responeData, SerializerFeature.WriteDateUseDateFormat);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write(jsonString);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            log.error("服务器异常: " + e.getMessage() + "\n" + MyUtils.getExceptionAllinformation(e));
        }
        return null;
    }

}